<?php

namespace app\common\model;

use think\Cache;
use think\cache\driver\Redis;
use think\Env;
use think\Log;
use think\Model;

/**
 * 微信推送
 */
class WxTui extends Model
{

    /**
     * 小程序推送-订单结束前提醒
     *
     * @param string $openid openid
     * @param string $order_id 参数
     * @param string $minutes 参数
     * @return Area 城市信息
     */
    public static function sendMessage($openid, $order_id,$minutes)
    {
//        $appid = Env::get('mini.appid');
//        $appsecret = Env::get('mini.secret');
        $touser = $openid;  //用户openid
        $minutes_str = "服务时间".$minutes."分钟";  //服务时间
        $template_id = 'O-XF62R_oEN-1a14KgrFh5Qa3RI47H8wNctBva7CmW8';//模板id
        $page = 'page/index'; //进入后跳转的页面
//        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
//        $res = json_decode(file_get_contents($url), true);
//        $access_token = $res['access_token'];

        $access_token = self::getAccessToken();
        //请求url
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token;

        //发送内容
        $data = [];

        //接收者（用户）的 openid
        $data['touser'] = $touser;

        //所需下发的订阅模板id
        $data['template_id'] = $template_id;

        //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
        $data['page'] = $page;
        //这里的值要对应模板详情的详细内容
        //模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
        $data['data'] = [
            "character_string1" => [
                'value' => $order_id, //订单号
            ],
            "thing3" => [
                'value' => $minutes_str,//服务时间
            ],
            "thing5" => [
                'value' => '您的咨询订单即将结束'//提醒文本
            ],
        ];

        //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
//        $data['miniprogram_state'] = 'formal为正式版';
        $data = json_encode($data);
        Log::info('小程序推送参数');
        Log::info($data);
        return self::curlPost($url, $data);
    }

    /**
     * 小程序推送-预约订单提醒
     *
     * @param string $openid openid
     * @param string $order_id 参数
     * @param string $start_time 参数
     */
    public static function sendMessage2($openid, $order_id,$start_time)
    {
//        $appid = Env::get('mini.appid');
//        $appsecret = Env::get('mini.secret');
        $touser = $openid;  //用户openid
        $start_times_str = "预约时间:".$start_time;  //预约
        $template_id = 'O-XF62R_oEN-1a14KgrFh5Qa3RI47H8wNctBva7CmW8';//模板id
        $page = 'page/index'; //进入后跳转的页面
//        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
//        $res = json_decode(file_get_contents($url), true);
//        $access_token = $res['access_token'];

        $access_token = self::getAccessToken();
        //请求url
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token;

        //发送内容
        $data = [];

        //接收者（用户）的 openid
        $data['touser'] = $touser;

        //所需下发的订阅模板id
        $data['template_id'] = $template_id;

        //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
        $data['page'] = $page;
        //这里的值要对应模板详情的详细内容
        //模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
        $data['data'] = [
            "character_string1" => [
                'value' => $order_id, //订单号
            ],
            "thing3" => [
                'value' => $start_times_str,//预约时间
            ],
            "thing5" => [
                'value' => '您有新的预约咨询订单'//提醒文本
            ],
        ];

        //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
//        $data['miniprogram_state'] = 'formal为正式版';
        $data = json_encode($data);
        Log::info('小程序推送参数');
        Log::info($data);
        return self::curlPost($url, $data);
    }


    public static function curlPost($url, $data)
    {
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $data;
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        return $content;
    }


    private static function  getAccessToken($force = false) {

        $access_token =Cache::get("weixin_access_token");//存入redis，这里要结合自己的项目，对redis或者memcahe进行设置
        Log::info('redis:'.$access_token);
        if(!$access_token || $force){
            $appId = Env::get('mini.appid');
            $appSecret = Env::get('mini.secret');
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
            $data = json_decode(getJson($url),true);
            Log::info('token:'.json_encode($data,true));
            if(isset($data['access_token']) && $data['access_token'] != ''){
                Cache::rm("weixin_access_token");
                Cache::set("weixin_access_token",$data['access_token'],7000);
                $access_token=$data['access_token'];
            }else{
                return false;
            }
        }
        return $access_token;
    }

    public static function gettoken()
    {
        return self::getAccessToken();
    }

}
